/**
 * 玩家工具函数
 * 提供玩家相关的实用工具函数
 */
import type { Player, PlayerStats, PlayerLevel } from '@/entities/Player';

/**
 * 计算玩家等级
 */
export function calculatePlayerLevel(experience: number): PlayerLevel {
  if (experience >= 3000) return 'master';
  if (experience >= 1500) return 'expert';
  if (experience >= 500) return 'professional';
  if (experience >= 100) return 'amateur';
  return 'novice';
}

/**
 * 计算升级到下一等级所需经验
 */
export function getExperienceForNextLevel(currentLevel: PlayerLevel): number {
  const levelThresholds = {
    novice: 100,
    amateur: 500,
    professional: 1500,
    expert: 3000,
    master: Infinity
  };
  return levelThresholds[currentLevel];
}

/**
 * 格式化游戏时长
 */
export function formatPlayTime(seconds: number): string {
  if (seconds < 60) return `${seconds}秒`;
  if (seconds < 3600) return `${Math.floor(seconds / 60)}分钟`;
  if (seconds < 86400) return `${Math.floor(seconds / 3600)}小时${Math.floor((seconds % 3600) / 60)}分钟`;
  
  const days = Math.floor(seconds / 86400);
  const hours = Math.floor((seconds % 86400) / 3600);
  return `${days}天${hours}小时`;
}

/**
 * 格式化最后活跃时间
 */
export function formatLastActive(lastActiveAt: string): string {
  const lastActive = new Date(lastActiveAt);
  const now = new Date();
  const diffMs = now.getTime() - lastActive.getTime();
  const diffMins = Math.floor(diffMs / 60000);
  const diffHours = Math.floor(diffMs / 3600000);
  const diffDays = Math.floor(diffMs / 86400000);
  
  if (diffMins < 1) return '刚刚';
  if (diffMins < 60) return `${diffMins}分钟前`;
  if (diffHours < 24) return `${diffHours}小时前`;
  if (diffDays < 7) return `${diffDays}天前`;
  if (diffDays < 30) return `${Math.floor(diffDays / 7)}周前`;
  if (diffDays < 365) return `${Math.floor(diffDays / 30)}个月前`;
  
  return `${Math.floor(diffDays / 365)}年前`;
}

/**
 * 计算玩家排名
 */
export function calculatePlayerRank(players: Player[], targetPlayerId: string, sortBy: keyof PlayerStats = 'totalScore'): number {
  const sortedPlayers = [...players].sort((a, b) => (b.stats[sortBy] as number) - (a.stats[sortBy] as number));
  const rank = sortedPlayers.findIndex(p => p.id === targetPlayerId) + 1;
  return rank || players.length + 1;
}

/**
 * 获取玩家统计摘要
 */
export function getPlayerStatsSummary(player: Player): {
  totalPlayTimeFormatted: string;
  lastActiveFormatted: string;
  solveRate: number;
  rank: number;
} {
  return {
    totalPlayTimeFormatted: formatPlayTime(player.totalPlayTime),
    lastActiveFormatted: formatLastActive(player.lastActiveAt),
    solveRate: player.stats.totalCases > 0 
      ? Math.round((player.stats.solvedCases / player.stats.totalCases) * 100)
      : 0,
    rank: player.stats.rank || 0
  };
}

/**
 * 验证玩家数据
 */
export function validatePlayerData(playerData: Partial<Player>): {
  isValid: boolean;
  errors: string[];
} {
  const errors: string[] = [];
  
  if (!playerData.username || playerData.username.length < 3) {
    errors.push('用户名至少需要3个字符');
  }
  
  if (playerData.username && playerData.username.length > 20) {
    errors.push('用户名不能超过20个字符');
  }
  
  if (!playerData.nickname || playerData.nickname.length < 2) {
    errors.push('昵称至少需要2个字符');
  }
  
  if (playerData.nickname && playerData.nickname.length > 30) {
    errors.push('昵称不能超过30个字符');
  }
  
  if (playerData.email && !isValidEmail(playerData.email)) {
    errors.push('邮箱格式不正确');
  }
  
  if (playerData.coins !== undefined && playerData.coins < 0) {
    errors.push('金币不能为负数');
  }
  
  if (playerData.gems !== undefined && playerData.gems < 0) {
    errors.push('宝石不能为负数');
  }
  
  if (playerData.experience !== undefined && playerData.experience < 0) {
    errors.push('经验值不能为负数');
  }
  
  return {
    isValid: errors.length === 0,
    errors
  };
}

/**
 * 验证邮箱格式
 */
function isValidEmail(email: string): boolean {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

/**
 * 生成默认玩家配置
 */
export function getDefaultPlayerPreferences() {
  return {
    theme: 'auto' as const,
    language: 'zh-CN',
    notifications: true,
    soundEffects: true,
    autoSave: true,
    difficulty: 'medium' as const,
    caseCategory: []
  };
}

/**
 * 生成默认玩家统计
 */
export function getDefaultPlayerStats(): PlayerStats {
  return {
    totalCases: 0,
    solvedCases: 0,
    failedCases: 0,
    currentStreak: 0,
    maxStreak: 0,
    totalScore: 0,
    averageScore: 0,
    totalTimeSpent: 0,
    averageTimePerCase: 0,
    accuracy: 0,
    rank: 0
  };
}

/**
 * 计算玩家活跃度
 */
export function calculatePlayerActivity(player: Player): {
  isActive: boolean;
  activityLevel: 'high' | 'medium' | 'low';
  lastActiveDays: number;
} {
  const lastActive = new Date(player.lastActiveAt);
  const now = new Date();
  const diffDays = Math.floor((now.getTime() - lastActive.getTime()) / 86400000);
  
  const isActive = diffDays <= 7 && player.isOnline;
  let activityLevel: 'high' | 'medium' | 'low' = 'low';
  
  if (diffDays <= 1) {
    activityLevel = 'high';
  } else if (diffDays <= 7) {
    activityLevel = 'medium';
  }
  
  return {
    isActive,
    activityLevel,
    lastActiveDays: diffDays
  };
}

/**
 * 获取玩家等级颜色
 */
export function getPlayerLevelColor(level: PlayerLevel): string {
  const levelColors = {
    novice: '#9e9e9e',
    amateur: '#4caf50',
    professional: '#2196f3',
    expert: '#ff9800',
    master: '#e91e63'
  };
  return levelColors[level];
}

/**
 * 获取玩家状态颜色
 */
export function getPlayerStatusColor(status: string): string {
  const statusColors = {
    active: '#4caf50',
    inactive: '#ff9800',
    banned: '#f44336',
    premium: '#9c27b0'
  };
  return statusColors[status as keyof typeof statusColors] || '#9e9e9e';
}